package com.gitee.dengmin.tenant.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gitee.dengmin.tenant.constants.TenantMap;
import com.gitee.dengmin.tenant.holder.TenantHolder;
import com.gitee.dengmin.tenant.mapper.TenantMapper;
import com.gitee.dengmin.tenant.models.Tenant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class RequestDomainInterceptor implements HandlerInterceptor {

    @Value("${domainSuffix}")
    private String domainSuffix;

    @Resource
    private TenantMapper tenantMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String serverName = request.getServerName();
        //截取域名 比如 test.cdn.system.me  domainSuffix=.cdn.system.me  那么截取打字符串test就是分配个商户的名字
        String tenantName = StringUtils.delete(serverName, domainSuffix);
        Tenant tenant = TenantMap.get(tenantName);
        if(null == tenant){
            QueryWrapper<Tenant> query = new QueryWrapper<>();
            query.eq("name", tenantName);
            tenant = tenantMapper.selectOne(query);
            if(null == tenant){
                throw new RuntimeException("找不到该商户名 => "+ tenantName);
            }
            TenantMap.put(tenant.getName(), tenant);
            return false;
        }
        TenantHolder.set(tenant);
        log.info("get tenant => {}", tenant);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TenantHolder.remove();
    }
}
